import LiveSession from './sequelize/LiveSession';
import { RoomService } from './Room';
import { Op } from 'sequelize';

export class LiveSessionService {
  private roomService = new RoomService();
  
  // 获取或创建当前活跃session
  async getOrCreateCurrentSession(roomId: string, title: string): Promise<string> {
    // 查询当前房间最新的session
    const latestSession = await LiveSession.findOne({
      where: { roomId },
      order: [['startTime', 'DESC']]
    });

    if (!latestSession) {
      // 如果没有session，创建新的
      return await this.createSession(roomId, title);
    }

    // 获取该session的最后一条消息时间
    const Message = (await import('./sequelize/Message')).default;
    const lastMessage = await Message.findOne({
      where: { 
        roomId,
        sessionId: latestSession.id 
      },
      order: [['createdAt', 'DESC']]
    });

    // 使用最后一条消息的时间作为session的结束时间
    let sessionEndTime = latestSession.endTime;
    if (lastMessage) {
      sessionEndTime = lastMessage.createdAt;
      // 更新session的结束时间
      await LiveSession.update(
        { endTime: sessionEndTime },
        { where: { id: latestSession.id } }
      );
    }

    const now = new Date();
    const oneHourAgo = new Date(now.getTime() - 60 * 60 * 1000);

    // 如果session的结束时间距离现在小于1小时，则复用
    if (sessionEndTime && sessionEndTime >= oneHourAgo || latestSession.startTime >= oneHourAgo) {
      // 更新title，确保title是最新的
      if (latestSession.title !== title) {
        await LiveSession.update(
          { title },
          { where: { id: latestSession.id } }
        );
        console.log(`✅ 更新session标题: ${latestSession.id}, 新标题: ${title}`);
      }
      return latestSession.id;
    }

    // 否则创建新session
    return await this.createSession(roomId, title);
  }

  // 创建新直播场次
  async createSession(roomId: string, title: string): Promise<string> {
    try {
      const session = await LiveSession.create({
        roomId,
        title,
        startTime: new Date()
      });
      
      console.log(`✅ 创建新session: ${session.id} for room ${roomId}, title: ${title}`);
      return session.id;
    } catch (error) {
      console.error('❌ 创建session失败:', error);
      throw error;
    }
  }

  // 结束直播场次
  async endSession(sessionId: string) {
    try {
      const Message = (await import('./sequelize/Message')).default;
      const lastMessage = await Message.findOne({
        where: { sessionId },
        order: [['createdAt', 'DESC']],
      });

      const endTime = lastMessage?.createdAt ?? new Date();

      await LiveSession.update(
        { endTime },
        { where: { id: sessionId } }
      );
      console.log(`✅ 结束session: ${sessionId}`);
    } catch (error) {
      console.error('❌ 结束session失败:', error);
    }
  }



  // 获取场次详情
  async getSession(sessionId: string) {
    return await LiveSession.findByPk(sessionId);
  }

  // 获取房间的历史场次
  async getRoomSessions(roomId: string, limit = 10) {
    return await LiveSession.findAll({
      where: { roomId },
      order: [['startTime', 'DESC']],
      limit
    });
  }

  // 获取当前活跃会话
  async getCurrentSession(roomId: string) {
    return await LiveSession.findOne({
      where: { 
        roomId,
        endTime: null // 未结束的会话
      },
      order: [['startTime', 'DESC']]
    });
  }
}
